﻿using SQLiteSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YunLuPos.Entity;

namespace YunLuPos.DB.Service
{
    public class SaleOrderAccountService
    {
        private log4net.ILog logger = log4net.LogManager.GetLogger(typeof(SaleOrderAccountService));

        public String addHisPayAccount(SaleOrder order, Dictionary<string, object> r)
        {

            if (r.ContainsKey("WX_FEE") && r.ContainsKey("POINT_FEE") && r.ContainsKey("PUB_FEE"))
            {
                DBLocker.setLocker();
                try
                {
                    Double wxFee = Double.Parse(r["WX_FEE"].ToString());
                    Double pointFee = Double.Parse(r["POINT_FEE"].ToString());
                    using (SqlSugarClient db = SugarDao.GetInstance())
                    {
                        db.BeginTran();
                        PayType p1 = db.Queryable<PayType>().Where(it => it.payTypeKey == "HISPAY").SingleOrDefault();
                        PayType p3 = db.Queryable<PayType>().Where(it => it.payTypeKey == "HPVER").SingleOrDefault();
                        SaleOrderAccount wa = new SaleOrderAccount();
                        wa.cliqueCode = order.cliqueCode;
                        wa.branchCode = order.branchCode;
                        wa.orderCode = order.orderCode;
                        wa.orderId = order.orderId;
                        wa.typeKey = p1.payTypeKey;
                        wa.masterTypeKey = p1.payTypeKey;
                        wa.typeName = p1.payTypeName;
                        wa.amount = wxFee;
                        long result = (Int64)db.Insert<SaleOrderAccount>(wa);
                        if (result <= 0)
                        {
                            return "HISPAY收单错误";
                        }

                        if (pointFee > 0)
                        {
                            SaleOrderAccount pa = new SaleOrderAccount();
                            pa.cliqueCode = order.cliqueCode;
                            pa.branchCode = order.branchCode;
                            pa.orderCode = order.orderCode;
                            pa.orderId = order.orderId;
                            pa.typeKey = p3.payTypeKey;
                            pa.masterTypeKey = p3.payTypeKey;
                            pa.typeName = p3.payTypeName;
                            pa.amount = pointFee;
                            long r3 = (Int64)db.Insert<SaleOrderAccount>(pa);
                            if (r3 <= 0)
                            {
                                db.RollbackTran();
                                return "HISPAY积分核销收单错误";
                            }
                        }
                        db.CommitTran();
                    }
                }
                catch
                {
                    return "支付结果值错误";
                }
                finally
                {
                    DBLocker.release();
                }
                return null;
            }
            else
            {
                return "支付返回结果错误";
            }
        }

        /**
         * 为订单添加支付流水、会员支付trandno为余额
         * */
        public String addAccount(SaleOrder order, PayType payType, PaymentState state, Double payAmount, String masterKey = null, String trandNo = null)
        {
            if (order == null || payType == null)
            {
                return "未指定订单或支付类型";
            }
            Console.WriteLine("------------account pay check");
            logger.Debug(payAmount);
            logger.Debug(state.less);
            logger.Debug((!"1".Equals(payType.isLessCent)) && payAmount > state.less);
            //不可溢收
            /*if (!"1".Equals(payType.isLessCent) && payAmount > state.less)
            {
                logger.Error("支付方式不可溢收");
                return "支付方式不可溢收";
            }*/
            DBLocker.setLocker();
            try
            {
                Console.WriteLine("22222" + trandNo);
                SaleOrderAccount account = new SaleOrderAccount();
                account.cliqueCode = order.cliqueCode;
                account.branchCode = order.branchCode;
                account.orderCode = order.orderCode;
                account.orderId = order.orderId;
                account.typeKey = payType.payTypeKey;
                account.masterTypeKey = masterKey;
                account.typeName = payType.payTypeName;
                account.amount = payAmount;
                account.trandNo = trandNo;
                if (masterKey == null)
                {
                    account.masterTypeKey = payType.payTypeKey;
                }
                using (SqlSugarClient db = SugarDao.GetInstance())
                {
                    Int64 result = (Int64)db.Insert<SaleOrderAccount>(account);
                    if (result > 0)
                    {
                        //可溢收项增加找零
                        if (payAmount > state.less)
                        {
                            SaleOrderAccount account2 = new SaleOrderAccount();
                            account2.cliqueCode = order.cliqueCode;
                            account2.branchCode = order.branchCode;
                            account2.orderCode = order.orderCode;
                            account2.orderId = order.orderId;
                            account2.typeKey = "CHANGE";
                            account2.typeName = "找零";
                            account2.amount = Math.Round(state.less - payAmount, 2);
                            result = (Int64)db.Insert<SaleOrderAccount>(account2);
                            if (result > 0)
                            {
                                return null;
                            }
                            else
                            {
                                return null;
                            }
                        }
                        else
                        {
                            return null;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
            finally
            {
                DBLocker.release();
            }
            return "收款错误请联系管理员";
        }


        /**
         * 获取单据支付明细
         * */
        public List<SaleOrderAccount> list(String orderCode)
        {
            DBLocker.setLocker();
            try
            {
                using (SqlSugarClient db = SugarDao.GetInstance())
                {
                    return db.Queryable<SaleOrderAccount>().Where(it => it.orderCode == orderCode).ToList();
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
            finally
            {
                DBLocker.release();
            }
            return null;
        }

        /**
        * 获取单据支付明细
        * */
        public List<String> listMasterKeys(String orderCode)
        {
            DBLocker.setLocker();
            try
            {
                using (SqlSugarClient db = SugarDao.GetInstance())
                {
                    return db.SqlQuery<String>("SELECT masterTypeKey FROM SaleOrderAccount where orderCode = @orderCode GROUP BY masterTypeKey "
                        , new { orderCode = orderCode }).ToList();
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
            finally
            {
                DBLocker.release();
            }
            return null;
        }
    }
}
